#! /usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2023-04-18 10:20
# @Author  : wsh
# @File    : admin_mapper.py
from model.db import reservoir_sensitivity
from model.db.user_model import TbAdmin, TbUsers
from model.params import RoleNameEnum
from util import DataNotExist, error_res, bcrypt_pwd
from util.encryption import verify_pwd
from util.exception_handlers import AllException, PwdNotMate


def add_admin():
    """
    添加管理员
    """
    if reservoir_sensitivity.query(TbUsers).filter(TbUsers.user_name == "admin").first()  is not None:
        return
    else:
        #  添加管理员
        admin = TbUsers(
            user_name="admin",
            user_pwd=bcrypt_pwd("123abc123"),
            role_name=RoleNameEnum.Admin,
            is_authorize=1,
            group_id=2,
        )
        reservoir_sensitivity.add(admin)
        reservoir_sensitivity.commit()
        reservoir_sensitivity.flush(admin)
        return


def admin_login(user_name, password):
    """
    管理员登录
    """
    admin = reservoir_sensitivity.query(TbAdmin).filter(TbAdmin.user_name == user_name).first()
    if admin is None:
        raise DataNotExist("管理员")

    if not verify_pwd(password, admin.user_pwd):
        raise PwdNotMate(admin.user_name)
    return admin
